extends Node2D

signal state_changed(new_state)

enum State{
	PATROL,
	ENGAGE
}

@export var angular_speed: float = 200.0  # 角速度（度/秒，示例：90度/秒）
@export var min_distance: float = 5.0 
@export var patrol_speed: float = 100.0

@onready var player_detection_zone = $PlayerDetectionZone
@onready var patrol_timer = $PatrolTimer

var current_state: int =State.PATROL : set=set_state
		
var player: Player = null
var weapon:Weapon = null
var actor:CharacterBody2D = null

var origin:Vector2 = Vector2.ZERO
var patrol_location: Vector2 = Vector2.ZERO
var patrol_location_reached: bool = false
var actor_velocity:Vector2 = Vector2.ZERO

func _ready():
	set_state(State.PATROL)

func _physics_process(delta):
	match current_state:
		State.PATROL:
			if not patrol_location_reached:
				actor.velocity = actor_velocity
				actor.move_and_slide()
				actor.rotate_toward(patrol_location)
				#actor.rotation = lerp(actor.rotation,actor.global_position.direction_to(patrol_location).angle(),0.1)
				if actor.global_position.distance_to(patrol_location) < 5:
					patrol_location_reached = true
					actor_velocity = Vector2.ZERO
					patrol_timer.start()
		State.ENGAGE:
			
			if player!=null and weapon!= null:
				#var angle_to_player = actor.global_position.direction_to(player.global_position).angle()
				actor.rotate_toward(player.global_position)
				if abs(actor.global_position.angle_to(player.global_position)) < 0.1:
					weapon.shoot()
			else:
				print("NO WEAPON OR NO PLAYER")
		_:
			print("ERROR:ENEMYPROCESSS")

func set_state(new_state: int):

	if new_state == current_state:
		return
	
	if new_state == State.PATROL:
		origin = actor.global_position
		patrol_timer.start()
		patrol_location_reached =true
	
	current_state = new_state
	emit_signal("state_changed",current_state)

func _on_player_detection_zone_body_entered(body):
	if body.is_in_group("player"):
		set_state(State.ENGAGE)
		player = body 

func initialize(actor:Enemy,weapon:Weapon):
	self.weapon =weapon
	self.actor= actor

func set_enemy_rotation(delta):
	# 1. 检查 player 是否存在（关键！）
	if player == null:
		print("错误：未绑定玩家节点")
		return
	
	# 2. 检查玩家是否在有效范围内（可选，调小 min_distance 测试）
	var distance = global_position.distance_to(player.global_position)
	if distance < min_distance:
		return  # 距离过近时停止转向
	
	# 3. 计算目标角度（玩家相对于角色的方向）
	var direction = global_position.direction_to(player.global_position)
	var target_angle = direction.angle()  # 目标角度（弧度，范围 [0, 2π)）
	
	# 4. 计算当前角度与目标角度的最短差值（调整到 [-π, π]）
	var current_angle = actor.rotation  # 当前旋转角度（弧度，范围 [0, 2π)）
	var angle_diff = target_angle - current_angle  # 初始差值（可能 > π 或 < -π）
	
	# 调整差值到 [-π, π] 范围内（关键！）
	if angle_diff > PI:
		angle_diff -= 2 * PI  # 例如：3π/2 → 3π/2 - 2π = -π/2（顺时针转90度）
	elif angle_diff < -PI:
		angle_diff += 2 * PI  # 例如：-3π/2 → -3π/2 + 2π = π/2（逆时针转90度）
	
	# 打印调试信息（关键！）
	
	# 5. 计算每帧应旋转的量（弧度/帧）
	var angular_speed_rad = deg_to_rad(angular_speed)  # 角速度转弧度/秒
	var rotate_amount = angular_speed_rad * delta  # 每帧旋转量（弧度）
	
	# 6. 根据角度差符号调整旋转方向（关键！）
	if angle_diff > 0:
		actor.rotation += rotate_amount  # 顺时针旋转（角度差为正）
	elif angle_diff < 0:
		actor.rotation -= rotate_amount  # 逆时针旋转（角度差为负）
	else:
		pass 
		
	  
func _on_player_detection_zone_body_exited(body):
	if player and body == player:
		set_state(State.PATROL)
		player = null


func _on_patrol_timer_timeout():
	var patrol_range = 50
	var random_x = randf_range(-patrol_range,patrol_range)
	var random_y = randf_range(-patrol_range,patrol_range)
	patrol_location =Vector2(random_x,random_y) + origin
	patrol_location_reached = false
	actor_velocity = actor.velocity_toward(patrol_location)
	
